package com.example.demo.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.aliyun.oss.OSS;
import com.example.demo.configuration.AliyunOssConfig;
import com.example.demo.controller.bean.Result;
import com.example.demo.dto.AddAdDTO;
import com.example.demo.dto.SelectedStudentRequestDTO;
import com.example.demo.mapper.entity.*;
import com.example.demo.service.AdManageService;
import com.example.demo.service.AdService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RequestMapping("adManage")
@Api(value = "广告管理接口", tags = {"广告管理接口"})
@RestController
@Slf4j
public class AdManageController {
    @Autowired
    private AdManageService service;

    @Autowired
    private AdService adService;
    private OSS ossClient;

    @ApiOperation(value = "添加广告接口")
    @PostMapping("/addAd")
    public Result<String> uploadCommodity(@RequestParam("imageFile") MultipartFile imageFile, @RequestParam("detailFile") MultipartFile detailFile, @RequestParam("addData") String addInfo) throws IOException {
        // 处理传入的 addData
        AddAdDTO request = new ObjectMapper().readValue(addInfo, AddAdDTO.class);
        int userId = StpUtil.getLoginIdAsInt();
        String detailUrl = null;
        //存储空间的名字
        String bucketName = "seedling-classmate";
        //创建存储对象
        ossClient = AliyunOssConfig.ossClient();
        //设置广告图片文件名并上传到OSS
        String imageFileName = imageFile.getOriginalFilename();//从上传的文件中获取原始文件名
        int i = imageFileName.lastIndexOf(".");
        String png1 = imageFileName.substring(i);//获取文件扩展名
        String imageUrl = "adImage/" + UUID.randomUUID().toString().substring(0,24)+png1;
        ossClient.putObject(bucketName, imageUrl, imageFile.getInputStream());   //之后在数据库中保存fileName
        //设置广告图片文件名并上传到OSS
        if(request.getAdType()==1){
            String detailFileName = detailFile.getOriginalFilename();//从上传的文件中获取原始文件名
            int a = detailFileName.lastIndexOf(".");
            String png2 = detailFileName.substring(a);//获取文件扩展名
            detailUrl = "adDetail/" + UUID.randomUUID().toString().substring(0,24)+png2;
            ossClient.putObject(bucketName, detailUrl, detailFile.getInputStream());   //之后在数据库中保存fileName
        }

        ossClient.shutdown();

        int resultId =service.addAdvertisement(request, imageUrl, detailUrl, userId);
        System.out.println("当前广告Id:"+resultId);
        //权重设置
        if (request.getAdType() == 2) {
            int studentResult = 0;
            int gender = request.getGender();
            int nativePlace = request.getNativePlace();
            int collegeId = request.getCollegeId();
            List<Student> studentList = service.getStudentList(gender, nativePlace, collegeId);
            System.out.println("推广学生："+studentList);
                for (Student student : studentList) {
                    double priority = calculatePriority(student.getId(), gender, collegeId, nativePlace);
                    System.out.println("推广权重："+priority);
                    service.addStudentAd(resultId, student.getId(), priority);
                }

            if(resultId!=0){
                return Result.ok("添加成功");
            }return Result.fail("添加失败");
        }
        if(resultId!=0){
            return Result.ok("添加成功");
        }
        return Result.fail("添加失败");

    }

    @PostMapping("getTotalStudent")
    @ApiOperation(value = "获取學生人數接口")
    @ResponseBody
    public int getTotalStudent(@RequestBody SelectedStudentRequestDTO studentData){
        System.out.println("当前学生数据："+studentData);
        return service.getTotalStudent(studentData);
    }

    public double calculatePriority(int studentId, int gender, int collegeId, int nativePlace) {
        Student student = adService.selectStudentById(studentId);
        System.out.println("当前计算权重学生信息："+student);
        double genderFactor = 0;
        double nativePlaceFactor = 0;
        double collegeFactor = 0;
        if(gender == 0){
            genderFactor =(double) 1 / adService.selectStudentCountByGender(0);  //男
            System.out.println("当前计算权重学生性别权重男："+adService.selectStudentCountByGender(0));
        }else if(gender == 1){
            genderFactor =(double) 1 / adService.selectStudentCountByGender(1);  //女
            System.out.println("当前计算权重学生性别权重女："+adService.selectStudentCountByGender(1));
        }
        if(nativePlace != 0){
            nativePlaceFactor =(double) 1 / adService.selectStudentCountByNativePlace(nativePlace);
        }
        System.out.println("当前计算权重学生籍贯权重："+adService.selectStudentCountByNativePlace(nativePlace));
        if(collegeId != 0){
            collegeFactor = (double) 1 / adService.selectStudentCountByCollege(collegeId);
        }
        System.out.println("当前计算权重学生学院权重："+adService.selectStudentCountByCollege(collegeId));
        AdSetting setting = adService.selectSetting();
        double genderWeight = setting.getGenderWeight() * genderFactor;
        double collegeWeight = setting.getCollegeWeight() * collegeFactor;
        double nativePlaceWeight = setting.getNativePlaceWeight() * nativePlaceFactor;
        double priority = genderWeight + collegeWeight + nativePlaceWeight;
        return priority;
    }

}
